package com.cuotoniu.lazybug.core.servlet;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cuotoniu.lazybug.common.util.MimeTypeUtil;

/**
 * This class for the Resource-Holding.But not the jsp(for time) 
 * 
 * @author HLJ
 *
 */
public class ResourceServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		service(req, resp);
	}

	@Override
	protected void doPut(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		service(req, resp);
	}

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		/** get the filename */
		String filename = req.getServletPath();
		/** get the file suffix */
		String[] suffix = filename.split("\\.");
		
		/** set the mime */
		resp.setContentType(MimeTypeUtil.getMimeType(suffix[suffix.length-1]));
		resp.setHeader("Accept-Ranges", "bytes");
		resp.setHeader("Server", "LazyBug");
		
		byte[] buffer = new byte[2048];	/** buffer length */
		int len = buffer.length;
		
		InputStream istream = null;			
		ServletOutputStream ostream = null;
		
		/** get the static resource */
		String path = req.getSession().getServletContext().getRealPath("/");
		filename = filename.replaceAll("/", "\\\\");	/** convert to the java format */
		File f = new File(path+filename);	
		istream = new FileInputStream(f);
		
		/** begin write the resource */
		BufferedInputStream bis = new BufferedInputStream(istream);
		try {
			ostream = resp.getOutputStream();
			while (true) {
				len = bis.read(buffer);
		        if (len == -1)
		        	break;
		        /** output the resource */
		        ostream.write(buffer, 0, len);
		    }
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}
